﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Loong.Model;

namespace QYWebSiteBN
{
    public class URLModelRule
    {
        private List<UrlModelInfo> ruleList = new List<UrlModelInfo>();

        public URLModelRule(string file)
        {
            Load(file);
        }
   
    
        /// <summary>
        /// 获得UrlModelInfo的数量
        /// </summary>
        public int Count
        {
            get { return ruleList.Count; }
        }

        /// <summary>
        /// 获取指ID的UrlModelInfo
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public UrlModelInfo Get(int index)
        {
            try
            {
                return ruleList[index];
            }
            catch
            {
                throw new OverflowException("数据不存在!");
            }
        }

        /// <summary>
        /// 添加网址规则
        /// </summary>
        /// <param name="info"></param>
        public void Add(UrlModelInfo info)
        {
            ruleList.Add(info);
        }

        /// <summary>
        /// 编辑网址规则
        /// </summary>
        /// <param name="index"></param>
        /// <param name="info"></param>
        public void Edit(int index, UrlModelInfo info)
        {

            if (ruleList[index] == null)
            {
                throw new OverflowException("没有找到指定的网址规则");
            }
            ruleList[index] = info;
        }


        /// <summary>
        /// 删除网址规则
        /// </summary>
        /// <param name="index"></param>
        public void Delete(int index)
        {
            if (ruleList[index] == null)
            {
                throw new OverflowException("没有找到指定的网址规则");
            }
            ruleList.RemoveAt(index);
        }


        /// <summary>
        /// 从文件载入数据
        /// </summary>
        public void Load(string filename)
        {
            Loong.Store.ObjectStoreQueue store = new Loong.Store.ObjectStoreQueue(filename);
            store.Load();
            int count=store.Count;
            for (int i = 0; i <count ; i++)
            {
                ruleList.Add((UrlModelInfo)store.Dequeue());
            }
        }

        /// <summary>
        /// 保存到储存文件
        /// </summary>
        /// <param name="filename"></param>
        public void Save(string filename)
        {
            try
            {
                Loong.Store.ObjectStoreQueue store = new Loong.Store.ObjectStoreQueue(filename);

                foreach (UrlModelInfo info in ruleList)
                {
                    store.Enqueue(info);
                }

                store.Save();
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
